const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//截取时间
function subTime(name) {
  var time = name.substring(0,4) + '-' + name.substring(4,6) + '-' + name.substring(6,8) + ' ' + name.substring(8,10) + ':' + name.substring(10,12);
  return time
}

//弹出层
function toast (msg){
  wx.showToast({
    title: msg,
    icon:'none'
  })
}

//时间戳转标准时间
function getTsFormatDate(timeStamp) {
  var date = new Date(timeStamp);
  // console.log(date); //结果为：Tue Apr 02 2019 07:49:23 GMT+0800 (中国标准时间)
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
      month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
  }

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();

  if (minutes >= 0 && minutes <= 9) {
      minutes = "0" + minutes;
  }

  if (seconds >= 0 && seconds <= 9) {
      seconds = "0" + seconds;
  }

  var currentdate = month + seperator1 + strDate  + ' ' +hours + ':' + minutes;
  return currentdate;
}


//获取用户的个人信息
function getSelfInfo(username) {
  var App = getApp();
  var JIM = App.globalData.jim
  return new Promise(function(success,fail) {
    JIM.getUserInfo({
      'username' : username
    }).onSuccess(function(data) {
        // console.log(data)
        success({'nickname':data.user_info.nickname,'avatar':data.user_info.avatar})

    }).onFail(function(data) {
        console.log(data);
    });
  });

}

//获取图片资源
function getResource (media_id) {
  var App = getApp();
  var JIM = App.globalData.jim
  return new Promise(function(success,fail) {
      JIM.getResource({
          'media_id' : media_id,
      }).onSuccess(function(data) {
          // console.log(data);
          success(data.url)
          //data.code 返回码
          //data.message 描述
          //data.url 资源临时访问路径，具体超时时间expire time会包含在url中
      }).onFail(function(data) {
          // codeError(data.code)
          //data.code 返回码
          //data.message 描述
      });
  });
}

//校验手机号
function phoneNumberVer (mobile){
  if (mobile.length == 0) {
      toast('请填写手机号');
      return false;
  }
  var myreg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0-9]|18[0-9]|19[89])\d{8}$/;
  if (mobile.length != 11 || !myreg.test(mobile)) {
      toast('请正确填写手机号');
      return false;
  }
  return true;
}

//封装请求
// const server = 'https://api.odancool.com';//正式服务器 必须为https
const server = 'https://apitest.odancool.com';//测试服务器 必须为https
const requestUrl = ({ url, params, success, method = "post" }) => {
  wx.showLoading({
    title: '加载中',
  });
  let headerPost = { 'content-type': 'application/x-www-form-urlencoded' }
  let headerGet = { 'content-Type': 'application/json' }
  return new Promise((resolve, reject) => {
    wx.request({
      url: server + url,
      method: method,
      data: params,
      header:{
      'content-type': 'application/x-www-form-urlencoded',
        'PUA':"wxsapp"
      },
      
      success: (res) => {
        wx.hideLoading();
        if (res['statusCode'] == 200) {
          resolve(res)//异步成功之后执行的函数
        } else {
          wx.showToast({
            title: res.data.msg || '请求出错',
            icon: 'none',
            duration: 2000,
            mask: true
          })
          reject(res.ErrorMsg);
        }
      },
      fail: (res) => {
        wx.hideLoading();
        wx.showToast({
          title: res.data.msg || '',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        reject('网络出错');
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  })
}

const requestGetUrl = ({ url, params, success, method = "get" }) => {
  wx.showLoading({
    title: '加载中',
  });
  let headerPost = { 'content-type': 'application/x-www-form-urlencoded' }
  let headerGet = { 'content-Type': 'application/json' }
  return new Promise((resolve, reject) => {
    wx.request({
      url: server + url,
      method: method,
      data: params,
      header:{
      'content-type': 'application/x-www-form-urlencoded',
        'PUA':"wxsapp"
      },
      
      success: (res) => {
        wx.hideLoading();
        if (res['statusCode'] == 200) {
          resolve(res)//异步成功之后执行的函数
        } else {
          wx.showToast({
            title: res.data.msg || '请求出错',
            icon: 'none',
            duration: 2000,
            mask: true
          })
          reject(res.ErrorMsg);
        }
      },
      fail: (res) => {
        wx.hideLoading();
        wx.showToast({
          title: res.data.msg || '',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        reject('网络出错');
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  })
}

/**
 * 执行请求，禁止多次点击或者重复点击
 */
function showLoading(message) {
  if (wx.showLoading) {
      // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
      wx.showLoading({
          title: message,
          mask: true
      });
  } else {
      // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
      wx.showToast({
          title: message,
          icon: 'loading',
          mask: true,
          duration: 20000
      });
  }
}

function hideLoading() {
  if (wx.hideLoading) {
      // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
      wx.hideLoading();
  } else {
      wx.hideToast();
  }
}
module.exports = {
  formatTime: formatTime,
  requestUrl: requestUrl,
  requestGetUrl:requestGetUrl,
  subTime:subTime,
  toast:toast,
  phoneNumberVer:phoneNumberVer,
  getTsFormatDate:getTsFormatDate,
  getResource:getResource,
  getSelfInfo:getSelfInfo,
  showLoading:showLoading,
  hideLoading:hideLoading
}
